package com.example.seckill.vo;

import com.example.seckill.utils.ValidatorUtil;
import com.example.seckill.validator.IsMobile;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @Author: Jason
 * @ClassName: IsMobileValidator
 * @Description: 手机号码校验规则
 * @Package：com.example.seckill.vo
 * @Project：seckill
 * @name：IsMobileValidator
 * @Filename：IsMobileValidator
 **/

public class IsMobileValidator implements ConstraintValidator<IsMobile,String> {

    private boolean required = false;

    @Override
    public void initialize(IsMobile constraintAnnotation) {
//        初始化获取是否为必填
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        //判断是否为必填
        if (required){
//            必填
            return ValidatorUtil.isMobile(value);
        }else {
//            非必填
            if (StringUtils.isEmpty(value)){
                return true;
            }else {
                return ValidatorUtil.isMobile(value);
            }
        }
    }


}
